﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.Message
{
    /// <summary>CCPSIP_031：機器人傳送檔案訊息 API(Photo,Document)</summary>
    /// SERVICE_ID = 機器人服務ID。
    /// Password = 機器人服務密碼。
    /// ChatID = 聊天ID（User 的 SIP_Num）。
    /// PPS_CODE = User 的員工編號。
    /// MobileNum = User 的手機門號（含國碼）。
    /// MsgType = 訊息類型，目前支援 ("P")。(Photo)
    /// 上傳檔案 = 要傳送給 User 的檔案。
    /// （ChatID / PPS_CODE / MobileNum至少須傳其中一個）

    public class robot_file_send : IHttpHandler
    {
        private string kFilesRootDir = ChrisKit.RootDir + "CCPSIP\\Files";//ios.ccp.com.tw
        private static Dictionary<string, string> kMsgTypeDirs = new Dictionary<string, string>() {
      { "P", "Photo" }, { "D", "Document" }
    };
        private const string kDateTimeFormat = "yyyy/MM/dd HH:mm:ss";
        private const int kFileSizeLimit = 101;//in MB


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】檢查呼叫端的 IP Address 是否合法
                //
                string ipAddr = ChrisKit.getIPAddress(req);
                if (!RobotKit.isAllowRobotIP(ipAddr))
                {
                    throw new Exception("ERROR_01: Access Denied");//拒絕存取
                }


                //【02】取得POST參數，驗證身分
                //
                string SERVICE_ID = req.Form["SERVICE_ID"];//機器人服務ID
                string Password = req.Form["Password"];    //機器人服務密碼
                string ChatID = req.Form["ChatID"];      //聊天ID(對方帳號或ClientGID)
                string PPS_CODE = req.Form["PPS_CODE"];  //長春員工編號
                string MobileNum = req.Form["MobileNum"];//接收方的手機號碼(含國碼)
                string MsgType = req.Form["MsgType"];//訊息類型
                int localPID = -1;//發訊方的本機訊息ID

                RobotServiceInfo rService = RobotKit.getServiceInfo(SERVICE_ID, Password);
                if (rService == null)
                {
                    throw new Exception("ERROR_02: Service Authentication Failed");//服務認證失敗
                }
                string ROBOT_ID = rService.ROBOT_ID;


                //【03】檢查UserID
                //
                if (string.IsNullOrEmpty(ChatID))
                {
                    string[] UserIDs;
                    if (string.IsNullOrEmpty(PPS_CODE))
                        UserIDs = OracleKitUser.getUserIDbyMobile(MobileNum);
                    else
                        UserIDs = OracleKitUser.getUserIDbyEmpID(PPS_CODE);

                    if (UserIDs != null && UserIDs.Length > 0)
                        ChatID = UserIDs[0];
                }

                if (!OracleKitUser.hasUser(ChatID))
                {
                    throw new Exception("ERROR_03: User not found");//找不到User
                }


                //【04】檢查上傳檔案
                //
                if (req.Files.Count < 1)
                {
                    throw new Exception("ERROR_04: No Upload File");//沒有上傳檔案
                }
                else if (req.Files[0].ContentLength < 512)
                {
                    throw new Exception("ERROR_05: The file is too small");//檔案太小
                }
                else if (req.Files[0].ContentLength > kFileSizeLimit * 1048576)
                {
                    throw new Exception("ERROR_05: The file is too large");//檔案太大
                }


                //【05】由訊息類型選擇副檔名
                //
                string fileTypeName = "";
                string fileTypeExt = "";
                if (MsgType == "P")
                {
                    fileTypeName = "photo";
                    fileTypeExt = ".jpg";
                }
                else if (MsgType == "D")
                {
                    fileTypeName = "document";
                    fileTypeExt = Path.GetExtension(req.Files[0].FileName).ToLower();
                }
                else
                {
                    throw new Exception("ERROR_06: Message type not support");//不支援的訊息類型
                }

                string msgPreview = string.Format("{0} sent you a {1}.", rService.ROBOT_CNAME, fileTypeName);


                //【06】儲存訊息
                //
                long MsgID = OracleKitMsg.InsertMsgOneWait(ROBOT_ID, ChatID, MsgType, msgPreview, localPID, reqTime);


                //【07】組合檔名路徑
                //
                string saveDir = string.Format(@"{0}\{1}\{2:yyyy}\{2:MM}", kFilesRootDir, kMsgTypeDirs[MsgType], reqTime);
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }

                string mainFileName = string.Format(@"{0:yyyyMMdd}_{1}_{2}{3}", reqTime, MsgID, SERVICE_ID, fileTypeExt);
                string mainFilePath = string.Format(@"{0}\{1}", saveDir, mainFileName);


                //【08】存檔，修改訊息檔名
                //
                req.Files[0].SaveAs(mainFilePath);

                string FileNameMsg = mainFileName;

                if (MsgType == "D")
                {
                    FileNameMsg = string.Format("{0}; {1}\n", mainFileName, req.Files[0].FileName);

                    double fileSizeKB = req.Files[0].ContentLength / 1024.0;
                    if (fileSizeKB < 1024)
                        FileNameMsg += string.Format("Size: {0:N0} KB", fileSizeKB);
                    else
                        FileNameMsg += string.Format("Size: {0:N1} MB", fileSizeKB / 1024.0);
                }

                OracleKitMsg.UpdateMsgOneFilename(ROBOT_ID, MsgID, FileNameMsg);


                //【09】Log機器人回覆
                //
                OracleKitRobot.InsertMsgOneRobot("R", ChatID, ROBOT_ID, SERVICE_ID, MsgID, FileNameMsg, reqTime);


                //【98】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【99】回傳結果
                //
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                resultDict["MsgID"] = Convert.ToString(MsgID);
                resultDict["MsgTime"] = reqTime.ToString(kDateTimeFormat);
                resultDict["Filename"] = FileNameMsg;

                resp.ContentType = "application/json";
                resp.Charset = "utf-8";
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
